from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import random
from ..models import FileStorage

order_bp = Blueprint('order', __name__)
orders = FileStorage('orders.json')
addresses = FileStorage('addresses.json')
products = FileStorage('products.json')

def generate_order_no():
    """生成订单号：年月日+6位随机数"""
    date = datetime.now().strftime('%Y%m%d')
    random_num = str(random.randint(100000, 999999))
    return date + random_num

def generate_logistics_no():
    """生成模拟物流单号"""
    return f"SF{random.randint(1000000, 9999999)}"

@order_bp.route('/orders', methods=['POST'])
@jwt_required()
def create_order():
    username = get_jwt_identity()
    data = request.get_json()
    items = data.get('items')
    address_id = data.get('address_id')
    payment = data.get('payment')
    
    # 验证地址
    address = addresses.find_one('id', address_id)
    if not address:
        return jsonify({'message': '收货地址不存在'}), 404
    
    # 验证商品并计算总价
    total_price = 0
    order_items = []
    for item in items:
        product = products.find_one('id', item['product_id'])
        if not product:
            return jsonify({'message': f'商品{item["product_id"]}不存在'}), 404
        
        order_items.append({
            'product_id': item['product_id'],
            'name': product['title'],
            'price': product['price'],
            'qty': item['qty']
        })
        total_price += product['price'] * item['qty']
    
    # 创建订单
    order = {
        'order_no': generate_order_no(),
        'username': username,
        'status': '待付款',
        'products': order_items,
        'address': address,
        'payment': payment,
        'total_price': total_price,
        'create_time': datetime.now().isoformat()
    }
    
    orders.insert(order)
    
    return jsonify({
        'order_no': order['order_no'],
        'status': order['status']
    })

@order_bp.route('/orders', methods=['GET'])
@jwt_required()
def get_orders():
    username = get_jwt_identity()
    status = request.args.get('status')
    
    # 获取用户订单
    user_orders = orders.find_many('username', username)
    
    if status:
        user_orders = [o for o in user_orders if o['status'] == status]
    
    # 模拟物流信息
    for order in user_orders:
        if order['status'] == '待收货':
            order['logistics'] = generate_logistics_no()
    
    return jsonify({
        'orders': [{
            'no': order['order_no'],
            'products': order['products'],
            'status': order['status'],
            'logistics': order.get('logistics')
        } for order in user_orders]
    })